<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="店铺" prop="jhTmId">
        <el-select v-model="queryParams.jhTmId" filterable placeholder="请选择店铺">
          <el-option v-for="item in tmAccountList" :key="item.jhId" :label="item.jhName" :value="item.jhId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据包" prop="jhDataId">
        <el-select v-model="queryParams.jhDataId" filterable placeholder="请选择数据包">
          <el-option v-for="item in dataPackageList" :key="item.jhId" :label="item.jhDataName" :value="item.jhId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板" prop="jhTemplateId">
        <el-select v-model="queryParams.jhTemplateId" filterable placeholder="请选择模板">
          <el-option v-for="item in templateList" :key="item.jhId" :label="item.jhTemplateName" :value="item.jhId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:task:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:task:edit']" :disabled="single" icon="el-icon-edit" plain size="mini" type="success" @click="handleUpdate">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:task:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:task:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column   key="jhDataPackageId" align="center" label="数据包" prop="jhDataId">
        <template slot-scope="scope">
          <el-tag size="small">{{ dataPackageList.find(x => x.jhId == scope.row.jhDataId) ? dataPackageList.find(x => x.jhId == scope.row.jhDataId).jhDataName : '' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column   key="jhTmId" align="center" label="天猫店铺" prop="jhTmId">
        <template slot-scope="scope">
          <el-tag size="small">{{ tmAccountList.find(x => x.jhId == scope.row.jhTmId) ? tmAccountList.find(x => x.jhId == scope.row.jhTmId).jhName : '' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column   key="jhTemplateId" align="center" label="模板" prop="jhTemplateId">
        <template slot-scope="scope">
          <el-tag size="small">{{ templateList.find(x => x.jhId == scope.row.jhTemplateId) ? templateList.find(x => x.jhId == scope.row.jhTemplateId).jhTemplateName : '' }}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column align="center" label="模板ID" prop="jhTemplateId"/>-->
<!--      <el-table-column align="center" label="进度" prop="jhProgress"/>-->
        <el-table-column align="center" label="状态" prop="jhStatus" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.jhStatus === 'waiting' ? 'primary' :
                   scope.row.jhStatus === 'processing' ? 'warning' :
                   scope.row.jhStatus === 'failed' ? 'danger' :
                   scope.row.jhStatus === 'cancel' ? 'info' :
                   'success'">
              {{ scope.row.jhStatus === 'waiting' ? '待处理' :
              scope.row.jhStatus === 'processing' ? '处理中' :
                scope.row.jhStatus === 'failed' ? '处理失败' :
                  scope.row.jhStatus === 'cancel' ? '已取消' :
                    '处理完成' }}
            </el-tag>
          </template>
        </el-table-column>
      <el-table-column align="center" label="成功数量" prop="jhSuccessNum"/>
      <el-table-column align="center" label="失败数量" prop="jhFailNum">
        <template slot-scope="scope">
          <el-link type="primary" @click="getProductOnSaleList(scope.row.jhId,'3')">{{ scope.row.jhFailNum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="过滤数量" prop="jhFiltrationNum">
        <template slot-scope="scope">
          <el-link type="primary" @click="getProductOnSaleList(scope.row.jhId,'1')">{{ scope.row.jhFiltrationNum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-hasPermi="['jihuo:task:start']" v-if="scope.row.jhStatus === 'processing'"   icon="el-icon-edit" size="mini" type="text" @click="handleProgress(scope.row)">
            查看进度
          </el-button>
          <el-button v-hasPermi="['jihuo:task:edit']"icon="el-icon-edit" size="mini" type="text" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button v-hasPermi="['jihuo:task:start']" v-if="scope.row.jhStatus === 'waiting'"   icon="el-icon-edit" size="mini" type="text" @click="handleStart(scope.row)">
            启动
          </el-button>
          <el-button v-hasPermi="['jihuo:task:start']" v-if="scope.row.jhStatus === 'failed'"   icon="el-icon-edit" size="mini" type="text" @click="handleAgainStart(scope.row)">
            重新启动
          </el-button>
          <el-button v-hasPermi="['jihuo:task:start']" v-if="scope.row.jhStatus === 'processing'"   icon="el-icon-edit" size="mini" type="text" @click="handleCancelStart(scope.row)">
            取消任务
          </el-button>
          <el-button v-hasPermi="['jihuo:task:remove']" icon="el-icon-delete" size="mini" type="text" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改发布天猫任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺" prop="jhTmId">
          <el-select v-model="form.jhTmId" filterable placeholder="请选择店铺">
            <el-option v-for="item in tmAccountList" :key="item.jhId" :label="item.jhName" :value="item.jhId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据包" prop="jhDataId">
          <el-select v-model="form.jhDataId" filterable placeholder="请选择数据包">
            <el-option v-for="item in dataPackageList" :key="item.jhId" :label="item.jhDataName" :value="item.jhId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板" prop="jhTemplateId">
          <el-select v-model="form.jhTemplateId" filterable placeholder="请选择模板">
            <el-option v-for="item in templateList" :key="item.jhId" :label="item.jhTemplateName" :value="item.jhId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 失败、过滤数量点击弹框 -->
    <el-dialog :title="productDialogTitle" :visible.sync="productDialogVisible" @close="handleDialogClose" append-to-body width="1000px">
      <el-table v-loading="productLoading" :data="ProductOnSaleList" stripe style="width: 100%">
        <el-table-column align="left" prop="jhOriginalUrl" label="原始链接" show-overflow-tooltip />
        <el-table-column align="left" prop="jhExplain" label="说明" width=500px />
      </el-table>
      <pagination v-show="ProductOnSaleListTotal>0" :limit.sync="productOnSaleQueryParams.pageSize" :page.sync="productOnSaleQueryParams.pageNum" :total="ProductOnSaleListTotal" @pagination="getProductOnSaleList(currentTaskId,currentStatus)"/>

    </el-dialog>
    <!-- 任务进度 -->
    <el-dialog
      :visible.sync="progressDialogVisible"
      width="30%"
      class="progress-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"> <!-- 明确禁用默认关闭按钮 -->

      <!-- 自定义关闭按钮 -->
      <div class="custom-close">
        <i class="el-icon-close" @click="closeProgressDialog"></i>
      </div>

      <div class="progress-container">
        <el-progress
          type="circle"
          :percentage="progressPercentage"
          class="center-progress">
        </el-progress>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addTask, delTask, getTask, listTask, updateTask, startTask, againStartTask, cancelTask} from "@/api/jihuo/task";
import {listData} from "@/api/jihuo/data";
import {listAccount} from "@/api/jihuo/account";
import {listTemplate} from "@/api/jihuo/template";
import {listSale} from "@/api/jihuo/productOnSale";

export default {
  name: "Task",
  data() {
    return {
      // 添加eventSource到data中
      eventSource: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dataPackageList: [],
      tmAccountList: [],
      templateList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      ProductOnSaleListTotal: 0,
      // 发布天猫任务表格数据
      taskList: [],
      ProductOnSaleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jhRevision: null,
        jhCreatedBy: null,
        jhCreatedTime: null,
        jhUpdatedBy: null,
        jhUpdatedTime: null,
        jhTmId: null,
        jhDataId: null,
        jhTemplateId: null,
        jhProgress: null,
        jhStatus: null,
        jhSuccessNum: null,
        jhFailNum: null,
        jhFiltrationNum: null,
        jhString001: null,
        jhString002: null
      },
      productLoading: false, // 加载状态
      currentTaskId: null, // 记录失败、过滤 任务ID
      currentStatus: null, // 记录失败、过滤 状态
      // 点击数量查询在售商品参数
      productOnSaleQueryParams: {
        pageNum: 1,
        pageSize: 10,
        jhDataPackageId: null,
        jhItemId: null,
        jhTmAccountId: null,
        jhName: null,
        jhStatus: '2',
        jhClass: null,
        jhOriginalUrl: null,
        jhListingTime: null,
        jhSalesVolume: null,
        jhTaskId: null,
      },
      progressDialogVisible: false,
      progressPercentage: 0,
      productDialogVisible: false, // 对话框显示状态
      productDialogTitle: '', // 对话框标题
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jhRevision: [
          {required: true, message: "乐观锁不能为空", trigger: "blur"}
        ],
        jhCreatedBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        jhCreatedTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        jhUpdatedBy: [
          {required: true, message: "更新人不能为空", trigger: "blur"}
        ],
        jhUpdatedTime: [
          {required: true, message: "更新时间不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  beforeDestroy() {
    // 组件销毁前清理资源
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  methods: {
    handleDialogClose() {
      // 重置分页参数
      this.productOnSaleQueryParams.pageNum = 1;
      this.productOnSaleQueryParams.pageSize = 10;
    },
    convertToPercentage(progressStr) {
      // 使用正则表达式提取已完成数量和总数量
      const regex = /(\d+)\/(\d+)/;
      const match = progressStr.match(regex);

      if (match && match.length === 3) {
        const completed = parseInt(match[1], 10);
        const total = parseInt(match[2], 10);

        // 计算百分比并四舍五入到两位小数
        const percentage = ((completed / total) * 100).toFixed(2);
        return percentage;
      } else {
        console.error("Invalid progress format");
        return null;
      }
    },
    closeProgressDialog() {
      if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
      }
      this.progressDialogVisible = false;
    },
    handleProgress(row) {
      if (row.jhStatus === "processing") {
        const url = `http://${process.env.VUE_APP_IP_PORT}${process.env.VUE_APP_BASE_API}/sse/task-progress?taskId=${row.jhId}`;
        console.log("url: ", url);
        // 如果已有连接，先关闭
        if (this.eventSource) {
          this.eventSource.close();
        }
        this.eventSource = new EventSource(url);
        this.eventSource.onmessage = (event) => {
          console.log("Message:", event.data);
        };

        this.eventSource.addEventListener("progress", (event) => {
          console.log("Progress:", event.data);
          const percentage = this.convertToPercentage(event.data);
          console.log(parseInt(percentage));
          this.progressPercentage = parseInt(percentage);
          this.progressDialogVisible = true;
        });

        this.eventSource.addEventListener("complete", (event) => {
          console.log("Task completed:", event.data);
          this.$modal.msgSuccess("任务已完成");
          this.progressPercentage = 100;
          this.progressDialogVisible = false;
          this.getList()
          this.eventSource.close();
        });
        this.eventSource.addEventListener("empty", (event) => {
          console.log("Task empty:", event.data);
          this.$modal.msgError("未获取到进度");
          this.eventSource.close();
        });

        this.eventSource.onerror = (error) => {
          console.error("Error:", error);
          this.eventSource.close();
        };
      }
    },
    getProductOnSaleList(taskId,status) {
      this.productDialogVisible = true
      this.currentTaskId = taskId
      this.currentStatus = status
      this.productOnSaleQueryParams.jhStatus = status;
      this.productOnSaleQueryParams.jhTaskId = taskId;
      this.productLoading = true;
      listSale(this.productOnSaleQueryParams).then(response => {
        this.productLoading = false;
        this.ProductOnSaleList = response.rows;
        this.ProductOnSaleListTotal = response.total;
      });
      this.productDialogTitle = status === '3' ? '失败商品列表' : '过滤商品列表';
    },
    /** 查询发布天猫任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listData().then(response => {
        this.dataPackageList = response.rows;
      });
      listAccount().then(response => {
        this.tmAccountList = response.rows;
      });
      listTemplate().then(response => {
        this.templateList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jhId: null,
        jhRevision: null,
        jhCreatedBy: null,
        jhCreatedTime: null,
        jhUpdatedBy: null,
        jhUpdatedTime: null,
        jhTmId: null,
        jhDataId: null,
        jhTemplateId: null,
        jhProgress: null,
        jhStatus: null,
        jhSuccessNum: null,
        jhFailNum: null,
        jhFiltrationNum: null,
        jhString001: null,
        jhString002: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发布天猫任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      getTask(jhId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发布天猫任务";
      });
    },
    handleStart(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      startTask(jhId).then(response => {
        if (response.code === 200){
          this.$modal.msgSuccess("后台处理中...");
        }else {
          this.$modal.msgError("发布失败");
        }
          this.getList();
      });
    },
    handleCancelStart(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      cancelTask(jhId).then(response => {
        this.getList();
      });
    },
    handleAgainStart(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      againStartTask(jhId).then(response => {
        if (response.code === 200){
          this.$modal.msgSuccess("后台处理中...");
        }else {
          this.$modal.msgError("重新发布失败");
        }
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jhId != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.jhStatus ==="processing"){
        debugger
        this.$modal.msgError("正在处理中，不能删除");
        return;
      }
      const jhIds = row.jhId || this.ids;
      this.$modal.confirm('是否确认删除发布天猫任务编号为"' + jhIds + '"的数据项？').then(function () {
        return delTask(jhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jihuo/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 原有样式保持不变 */
.progress-dialog >>> .el-dialog {
  background-color: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative; /* 为绝对定位的关闭按钮提供参考 */
}

.progress-dialog >>> .el-dialog__body {
  padding: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 进度容器样式 */
.progress-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

/* 居中进度圈 */
.center-progress {
  margin: 0 auto;
  width: 150px;
  height: 150px;
}

.center-progress >>> .el-progress-circle {
  width: 100% !important;
  height: 100% !important;
}

/* 进度文字 */
.progress-text {
  margin-top: 20px;
  color: #fff;
  font-size: 16px;
  text-align: center;
}

/* 自定义关闭按钮样式 */
.custom-close {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 10;
}

.custom-close .el-icon-close {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s;
}

.custom-close .el-icon-close:hover {
  color: #409EFF;
}
</style>
